package com.edu.admin.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * redis操作
 * 
 * @author Wangjiong
 * 
 */
public class JedisUtil {
	
	private static String JEDIS_IP;
	private static int JEDIS_PORT;
	private static String JEDIS_PASSWORD;
	
	private static JedisPool jedisPool;
	static {

		JEDIS_IP = YamlUtil.getValue("jedis.ip");
		JEDIS_PORT = Integer.valueOf(YamlUtil.getValue("jedis.port"));
		JEDIS_PASSWORD = YamlUtil.getValue("jedis.password");
		JedisPoolConfig config = new JedisPoolConfig();

		
		config.setMaxTotal(200);
		config.setMaxIdle(50);
		config.setMinIdle(8);//设置最小空闲数
		config.setMaxWaitMillis(10000);
		config.setTestOnBorrow(true);
		config.setTestOnReturn(true);
		//Idle时进行连接扫描
		config.setTestWhileIdle(true);
		//表示idle object evitor两次扫描之间要sleep的毫秒数
		config.setTimeBetweenEvictionRunsMillis(30000);
		//表示idle object evitor每次扫描的最多的对象数
		config.setNumTestsPerEvictionRun(10);
		//表示一个对象至少停留在idle状态的最短时间，然后才能被idle object evitor扫描并驱逐；这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
		config.setMinEvictableIdleTimeMillis(60000);
		
		jedisPool = new JedisPool(config, JEDIS_IP, JEDIS_PORT, 60000, JEDIS_PASSWORD);
	}

	/**
	 * 获取数据
	 * 
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		String value = null;
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			value = jedis.get(key);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(jedis);
		}
		return value;
	}

	public static void set(String key, String value, int time) {

		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.set(key, value);
			jedis.expire(key, time);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(jedis);
		}
	}
	
	public static void del(String key) {

		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.del(key);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(jedis);
		}
	}

	private static void close(Jedis jedis) {
		try {
			if (jedis != null) {
				jedis.close();
			}
		} catch (Exception e) {
			if (jedis.isConnected()) {
				jedis.quit();
				jedis.disconnect();
			}
		}
	}

	
}
